from orion.modules.SubtitleEngine import SubtitleEngine
from orion.util.FileUtil import FileUtil
from orion.util.GZIPUtil import GZIPUtil
from orion.util.HashFile import HashFile
import xmlrpclib

class OpenSubtitle(SubtitleEngine):
    
    __RPC_API_URL = "http://api.opensubtitles.org/xml-rpc"
    __USER_AGENT = "OS Test User Agent"
    __SUB_EXTENSION = "srt"
    
    def __init__(self):
        super(OpenSubtitle, self).__init__()
        try:
            self.server = xmlrpclib.Server(self.__RPC_API_URL)
            result = self.server.LogIn("", "", "en", self.__USER_AGENT)
            self.__token = result["token"]
        except Exception:
            self.__token = None
    
    def search(self, files):
        super(OpenSubtitle, self).search(files)
        self.__hashReference = {}
        search = []
        for file in files:
            search.append(self.__search_input(file))
        
        output = self.server.SearchSubtitles(self.__token, search)
        if output["data"] is False:
            self.subtitles = None
        else:
            self.__parse_output(output["data"])
    
    def __search_input(self, file):
        hashFile = HashFile(file)
        hash = hashFile.hash()
        dir, name = FileUtil.info(file)
        self.__hashReference[hash] = {"Destination" : dir, "Name" : name}
        
        fileSearch = {}
        fileSearch["moviehash"] = hash
        fileSearch["moviebytesize"] = str(hashFile.size())
        fileSearch["sublanguageid"] = ",".join(self.languages)
        return fileSearch

    def __parse_output(self, data):
        for subtitle in data:
            fileReference = self.__hashReference[subtitle["MovieHash"]]
            id = subtitle["IDSubtitleFile"]
            self.subtitles[id] = fileReference
            

    def __was_searched_before(self):
        return self.subtitles is not None and len(self.subtitles) > 0

    def download(self):
        super(OpenSubtitle, self).download()
        output = None
        if self.__was_searched_before():
            subtitleIds = []
            for key in self.subtitles:
                subtitleIds.append(key)
            output = self.server.DownloadSubtitles(self.__token, subtitleIds)
        
        for subtitleData in output["data"]:
            file, dataB64 = self.__parse_download(subtitleData)
            self.SubtitleWriter.write(file, dataB64)
        
    def __parse_download(self, subtitleData):
        subId = subtitleData["idsubtitlefile"]
        file = "".join([self.subtitles[subId]["Destination"], "\\", self.subtitles[subId]["Name"], ".", self.__SUB_EXTENSION])
        textB64 = subtitleData["data"]
        return [file, textB64]
            
    def close(self):
        self.server.LogOut(self.__token)
        

    class SubtitleWriter(object):
        @classmethod
        def write(cls, file, b64Data):
            subtitleContent = GZIPUtil.unzip(b64Data)
            FileUtil.write(file, subtitleContent)
        